#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "storefile.h"

int isExist(char *filename)
{
	return (access(filename, 0) == 0);
}

int createFile(char *filename)
{
	FILE *fp; 
    if ((fp = fopen(filename, "w")) == NULL) {
        return 0;
    } else {
        fclose(fp);
        return 1;
    }
}

int file_put_contents(char *filename, char *words)
{
	FILE *fp;
	if ((fp = fopen(filename, "a+")) == NULL) {
       	return 0;
   	} else {
		fputs(words, fp);
		fclose(fp);
	}
	return 1;
}

int write_bakup_words(char *filename, char *words, char *type, char *remote_ip)
{
	int len, ok;
	char *key;
	len = 5 + strlen(words) + 15;
	key = (char *) malloc(len+1);
	if (key == 0) {
		free(key);
		return 0;
	}
	memset(key, '\0', len+1);
	strcat(key, type);
	strcat(key, "|");
	strcat(key, words);
	strcat(key, "|");
	strcat(key, remote_ip);
	strcat(key, "\n");
	ok = file_put_contents(filename, key);
	free(key);
	return ok;
}
